
#include "entity.h"

using namespace std;

Entity::Entity(const std::string& _name, const int& _health, const int& _attack, const int& _defense, const int& _speed) :
    name(_name), maxHealth(_health), currentHealth(_health), attack(_attack), defense(_defense), speed(_speed), currentSpeed(_speed)
{
    //null;
}

void Entity::writeStats() const
{
    // displays combat statistics
    cout << name << endl;
    cout << "Attack: " << getAttack() << "\tDefense: " << getDefense() << "\tSpeed: " << getCurrentSpeed() << "/" << getSpeed() << endl;
    cout << "Health: " << getHealth() << "/" << getMaxHealth() << endl;
}

void Entity::takeDamage(const double& d)
{
    if (d > 0)
    {
        currentHealth -= d;
    }
}

void Entity::startCombat()
{
    // clears buffs, sets current health and current speed
    list<Buff>::iterator it = buffs.begin();
    while (it != buffs.end())
    {
        attack -= it->getStrength(Attack);
        defense -= it->getStrength(Defense);
        speed -= it->getStrength(Speed);
        it = buffs.erase(it);
    }
    currentHealth = maxHealth;
    currentSpeed = speed;
}

void Entity::tick()
{
    // ticks buffs once (reduces remaining duration by 1), removes expired ones and their effects
    list<Buff>::iterator it = buffs.begin();
    while (it != buffs.end())
    {
        it->tick();
        if (it->isExpired())
        {
            attack -= it->getStrength(Attack);
            defense -= it->getStrength(Defense);
            speed -= it->getStrength(Speed);
            it = buffs.erase(it);
        }
        else
        {
            ++it;
        }
    }
}

void Entity::addBuff(const Buff& b)
{
    // adds a buff and its effects or remoes one if the ID is already in use
    if (b.getID() == "")
    {
        buffs.push_back(b);
        attack += b.getStrength(Attack);
        defense += b.getStrength(Defense);
        speed += b.getStrength(Speed);
    } else
    {
        bool found = false;
        for (list<Buff>::iterator it = buffs.begin(); !found && it != buffs.end(); ++it)
        {
            if (it->getID() == b.getID())
            {
                found = true;
                attack -= it->getStrength(Attack);
                defense -= it->getStrength(Defense);
                speed -= it->getStrength(Speed);
                buffs.erase(it);
            }
        }
        if (!found)
        {
            buffs.push_back(b);
            attack += b.getStrength(Attack);
            defense += b.getStrength(Defense);
            speed += b.getStrength(Speed);
        }
    }
}

